package com.gin.kotlin.vegetables_kot.interceptor

import android.util.Log
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.text.DecimalFormat
import java.util.Locale

/**
 * 请求日志拦截器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/9 10:49
 */
class LoggingInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val url = request.url.toString()
        val startTime = System.nanoTime()
        Log.d(
            TAG, String.format(
                Locale.CHINA,
                "[%s] 发送请求: %s",
                request.method,
                url
            )
        )
        //            Log.d(TAG, String.valueOf(request.headers()));
        val response: Response = chain.proceed(request)

        val endTime = System.nanoTime()

        var msg = String.format(
            Locale.CHINA,
            "[%s] 响应请求: %s code: %d cost: %.1fms",
            request.method,
            url,
            response.code,
            (endTime - startTime) / 1e6
        )
        val contentLength = response.header("Content-Length")
        if (contentLength != null) {
            msg += " length: " + DECIMAL_FORMAT.format(contentLength.toLong())
        }
        Log.d(TAG, msg)
        // 重定向
        if (response.code / 100 == 3) {
            Log.w(TAG, "重定向: " + response.header("location"))
        }

        return response
    }

    companion object {
        private val TAG: String = LoggingInterceptor::class.java.simpleName
        private val DECIMAL_FORMAT = DecimalFormat("###,###.##")
    }
}
